----------------------------------------------------------------
-- Global Variables
----------------------------------------------------------------

SocialWindowTabGuild = {}
SocialWindowTabGuild.playerListData = {}
SocialWindowTabGuild.playerListOrder = {}

-- Sorting Parameters for the Player List
SocialWindowTabGuild.SORT_TYPE_NAME	 		= 1
SocialWindowTabGuild.SORT_TYPE_RANK			= 2
SocialWindowTabGuild.SORT_TYPE_CAREER	        = 3
SocialWindowTabGuild.SORT_TYPE_ONLINE	        = 4
SocialWindowTabGuild.SORT_TYPE_MAX_NUMBER     = 4

SocialWindowTabGuild.FILTER_MEMBERS_ALL	    = 1
SocialWindowTabGuild.FILTER_MAX_NUMBER		= 1

SocialWindowTabGuild.SORT_ORDER_UP	        = 1
SocialWindowTabGuild.SORT_ORDER_DOWN	        = 2

SocialWindowTabGuild.sortButtons = {  "SocialWindowTabGuildSortButtonBarNameButton",		-- Order List Header 
                                    "SocialWindowTabGuildSortButtonBarRankButton", 
                                    "SocialWindowTabGuildSortButtonBarCareerButton", 
                                    "SocialWindowTabGuildSortButtonBarOnlineButton" }
                                    
-- Make sure these match the ID numbers in the XML definition 
--    For example,  <Button name="$parentNameButton" inherits="SocialHeaderButton" id="1"> 
SocialWindowTabGuild.sortKeys = {"name",
                               "rank", 
                               "career", 
                               "online"  }

SocialWindowTabGuild.sortColumns = { "Name", 
                                   "Rank", 
                                   "Career", 
                                   "Online"  }
SocialWindowTabGuild.display = { type=SocialWindowTabGuild.SORT_TYPE_NAME, 
                                order=SocialWindowTabGuild.SORT_ORDER_UP, 
                                filter=SocialWindowTabGuild.FILTER_MEMBERS_ALL }
SocialWindowTabGuild.ColumnHeaders = {   
                                GetStringFromTable( "SocialStrings", StringTables.Social.LABEL_SOCIAL_SORT_BUTTON_NAME),
                                GetStringFromTable( "SocialStrings", StringTables.Social.LABEL_SOCIAL_SORT_BUTTON_RANK),
                                GetStringFromTable( "SocialStrings", StringTables.Social.LABEL_SOCIAL_SORT_BUTTON_CAREER),
                                GetStringFromTable( "SocialStrings", StringTables.Social.LABEL_SOCIAL_FRIENDS_BUTTON_GUILDNAME) }
                                      
SocialWindowTabGuild.SelectedPlayerDataIndex    = 0
SocialWindowTabGuild.SelectedFriendsName        = L""

SocialWindowTabGuild.OptionsLocked = 0

local function InitPlayerListData()
    SocialWindowTabGuild.playerListData = {}
    local atLeastOne = false

    local GuildListData = GetLFMList()	-- @TODO: Replace with Guild List
    
     if ( GuildListData ~= nil ) then
        for key, value in ipairs( GuildListData ) do
            atLeastOne = true
            -- These should match the data that was retrived from war_interface::LuaGetFriendsList
            SocialWindowTabGuild.playerListData[key] = {}
            SocialWindowTabGuild.playerListData[key].name = value.name
            SocialWindowTabGuild.playerListData[key].rank = value.rank
            SocialWindowTabGuild.playerListData[key].career = value.career
            SocialWindowTabGuild.playerListData[key].online = value.guildName
        end
    end

    if (atLeastOne == false) then
            SocialWindowTabGuild.playerListData[1] = {}
            SocialWindowTabGuild.playerListData[1].name = L"NO RESULTS"
    end
end

-- This function is used as the comparison function for 
-- table.sort() on the player display order
local function ComparePlayers( index1, index2 )

    if( index2 == nil ) then
        return false
    end

    local player1 = SocialWindowTabGuild.playerListData[index1]
    local player2 = SocialWindowTabGuild.playerListData[index2]
    
    local type = SocialWindowTabGuild.display.type
    local order = SocialWindowTabGuild.display.order
    
    local compareResult
-- Check for sorting by all the the string fields first
    
    -- Sorting by Name
    if( type == SocialWindowTabGuild.SORT_TYPE_NAME )then
        if( order == SocialWindowTabGuild.SORT_ORDER_UP ) then
            return ( WStringsCompare(player1.name, player2.name) < 0 )
        else
            return ( WStringsCompare(player1.name, player2.name) > 0 )
        end
    end
    
    --Sorting By Career (And if they match, then sort alphabetically)
    if( type == SocialWindowTabGuild.SORT_TYPE_CAREER ) then
        compareResult = WStringsCompare(player1.career, player2.career)
        
        if (compareResult == 0) then
            return ( WStringsCompare(player1.name, player2.name) < 0 )
        end
        
        if( order == SocialWindowTabGuild.SORT_ORDER_UP ) then
            return ( compareResult < 0 )
        else
            return ( compareResult > 0 )
        end		
    end

    -- Sorting By Online (And if they match, then sort alphabetically)
    if( type == SocialWindowTabGuild.SORT_TYPE_ONLINE ) then
        compareResult = WStringsCompare(player1.online, player2.online)
        
        if (compareResult == 0) then
            return ( WStringsCompare(player1.name, player2.name) < 0 )
        end	
        
        if( order == SocialWindowTabGuild.SORT_ORDER_UP ) then
            return ( compareResult < 0)
        else
            return ( compareResult > 0)
        end
    end

-- Otherwise assume we're sorting by a number, not a string.
    -- Sorting By A Numerical Value - When tied, sort by name
    local key = SocialWindowTabGuild.sortKeys[type]
    if( order == SocialWindowTabGuild.SORT_ORDER_UP ) then			
        if( player1[key] == player2[key] ) then
            return ( WStringsCompare(player1.name, player2.name) < 0 )
        else		
            return ( player1[key] < player2[key] )
        end
    else
        if( player1[key] == player2[key] ) then
            return ( WStringsCompare(player1.name, player2.name) < 0 )
        else		
            return ( player1[key] > player2[key] )
        end
    end	
    
end
local function SortPlayerList()	
    table.sort( SocialWindowTabGuild.playerListOrder, ComparePlayers )
end

local function FilterPlayerList()	
    
    local filter = SocialWindowTabGuild.display.filter

    SocialWindowTabGuild.playerListOrder = {}
    for dataIndex, data in ipairs( SocialWindowTabGuild.playerListData ) do
        table.insert(SocialWindowTabGuild.playerListOrder, dataIndex)
    end
end

local function UpdatePlayerList()
    -- Filter, Sort, and Update
    InitPlayerListData()
    SocialWindowTabGuild.display.filter = SocialWindowTabGuild.FILTER_MEMBERS_ALL
    FilterPlayerList()
    SortPlayerList()
    ListBoxSetDisplayOrder( "SocialWindowTabGuildList", SocialWindowTabGuild.playerListOrder )
end

-- OnInitialize Handler
function SocialWindowTabGuild.Initialize()

    -- Set all the header labels
    LabelSetText( "SocialWindowTabGuildOptionsHeaderInterest", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_PARTY_OPTIONS_HEADER) )
    LabelSetText( "SocialWindowTabGuildGoalHeader", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_PARTY_GOALS_HEADER) )
    LabelSetText( "SocialWindowTabGuildNotesHeader", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_PARTY_PLAYER_NOTES_HEADER) )
    
    WindowSetTintColor("SocialWindowTabGuildOptionsBackground", 0, 0, 0 )

    -- Set The options buttons as being check-able
    ButtonSetCheckButtonFlag("SocialWindowTabGuildOptions1", true )
    ButtonSetCheckButtonFlag("SocialWindowTabGuildOptions2", true )
    ButtonSetCheckButtonFlag("SocialWindowTabGuildOptions3", true )

    ButtonSetCheckButtonFlag("SocialWindowTabGuildGoal1Button", true )
    ButtonSetCheckButtonFlag("SocialWindowTabGuildGoal2Button", true )
    ButtonSetCheckButtonFlag("SocialWindowTabGuildGoal3Button", true )
    ButtonSetCheckButtonFlag("SocialWindowTabGuildGoal4Button", true )
    
    ButtonSetCheckButtonFlag("SocialWindowTabGuildSearchToggleButton", true )

    -- Set the labels for the buttons
    LabelSetText("SocialWindowTabGuildOptions1Label", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_PARTY_OPTIONS1) )
    LabelSetText("SocialWindowTabGuildOptions2Label", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_PARTY_OPTIONS2) )
    LabelSetText("SocialWindowTabGuildOptions3Label", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_PARTY_OPTIONS3) )

    LabelSetText("SocialWindowTabGuildGoal1Label", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_PARTY_GOAL1) )
    LabelSetText("SocialWindowTabGuildGoal2Label", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_PARTY_GOAL2) )
    LabelSetText("SocialWindowTabGuildGoal3Label", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_PARTY_GOAL3) )
    LabelSetText("SocialWindowTabGuildGoal4Label", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_PARTY_GOAL4) )

    LabelSetText("SocialWindowTabGuildSearchToggleLabel", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_PARTY_TOGGLE) )

    -- Set the text for all the buttons
    ButtonSetText("SocialWindowTabGuildSetButton", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_PARTY_SET_BUTTON) )
    ButtonSetText("SocialWindowTabGuildFindButton", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_PARTY_FIND_BUTTON) )
    
    -- Setup the listbox
    ButtonSetText( "SocialWindowTabGuildSortButtonBarNameButton",  GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_SORT_BUTTON_NAME) )
    ButtonSetText( "SocialWindowTabGuildSortButtonBarRankButton",	GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_SORT_BUTTON_RANK) )
    ButtonSetText( "SocialWindowTabGuildSortButtonBarCareerButton", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_SORT_BUTTON_CAREER) )
    ButtonSetText( "SocialWindowTabGuildSortButtonBarOnlineButton", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_SORT_BUTTON_LOCATION) )
    SocialWindowTabGuild.SetListRowTints()
    SocialWindowTabGuild.OnGuildUpdated()
    SocialWindowTabGuild.UpdateSortButtons()	

end

function SocialWindowTabGuild.Shutdown()

end

function SocialWindowTabGuild.OnPressSetGuildButton()
    if SocialWindowTabGuild.OptionsLocked == 0 then
        SocialWindowTabGuild.OptionsLocked = 1
        ButtonSetText("SocialWindowTabGuildSetButton", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_GUILD_UNSET_BUTTON) )
        WindowSetTintColor("SocialWindowTabGuildOptionsBackground", 64, 64, 64 )
    else
        SocialWindowTabGuild.OptionsLocked = 0
        ButtonSetText("SocialWindowTabGuildSetButton", GetStringFromTable("SocialStrings", StringTables.Social.LABEL_SOCIAL_GUILD_SET_BUTTON) )
        WindowSetTintColor("SocialWindowTabGuildOptionsBackground", 0, 0, 0 )
    end
end



function SocialWindowTabGuild.UpdateSelectedPlayerData( dataIndex )
    -- Set the label values
    if (dataIndex ~= nil) then
        SocialWindowTabGuild.SelectedPlayerDataIndex = dataIndex
    else
        SocialWindowTabGuild.SelectedPlayerDataIndex = 0
        SocialWindowTabGuild.SelectedFriendsName = L""
    end
end

-- Assigns all the labels to all the rows, as well as highlighting the selected row
function SocialWindowTabGuild.HighlightPlayerInList( windowName, bSelected, bFromLButtonEvent, bFromRButtonEvent )

    local windowIndex	= WindowGetId (windowName)
    local windowParent	= WindowGetParent (windowName)

    -- Get the player's indexed data from the GameData list and update the lower fields
    local dataIndex = ListBoxGetDataIndex (WindowGetParent (windowParent), windowIndex)

    if (bFromLButtonEvent or bFromRButtonEvent) then
        -- If the player is already selected, unselect it unless this was a RButton event.
        if (dataIndex ~= SocialWindowTabGuild.SelectedPlayerDataIndex or bFromRButtonEvent ) then
            SocialWindowTabGuild.UpdateSelectedPlayerData(dataIndex)
            SocialWindowTabGuild.SelectedFriendsName = LabelGetText(WindowGetParent (windowParent).."Row"..windowIndex.."Name")
            SocialWindowTabGuild.UpdatePlayerRow()	-- Clear selected player info from list
        else
            bSelected = false
            SocialWindowTabGuild.UpdateSelectedPlayerData(0)
            --WindowSetShowing("GuildWindowGuildNoteEditBox", false)
        end
    end

    -- Change colors based on if the guild member is selected, offline, or online
    local labelOnlineText = LabelGetText(WindowGetParent (windowParent).."Row"..windowIndex.."Online")
    local bIsOnline = false
    
    if ( WStringsCompare( labelOnlineText, GetStringFromTable( "SocialStrings", StringTables.Social.LABEL_SOCIAL_SORT_BUTTON_ONLINE) ) == 0 ) then
        bIsOnline = true
    end
    
    local labelColor = { r=255, g=255, b=255 }		-- Default Online Memebers are white
    
    if (bIsOnline == false) then
        labelColor = { r=140, g=140, b=140 }		-- Offline Members are grey
    end
    
    if (bSelected) then		  
        labelColor = { r=255, g=204, b=102 }		-- Selected member is yellow, regardless if member is offline or not
    end
    
    LabelSetTextColor (WindowGetParent (windowParent).."Row"..windowIndex.."Name", labelColor.r, labelColor.g, labelColor.b)
    LabelSetTextColor (WindowGetParent (windowParent).."Row"..windowIndex.."Rank", labelColor.r, labelColor.g, labelColor.b)
    LabelSetTextColor (WindowGetParent (windowParent).."Row"..windowIndex.."Career", labelColor.r, labelColor.g, labelColor.b)
    LabelSetTextColor (WindowGetParent (windowParent).."Row"..windowIndex.."Online", labelColor.r, labelColor.g, labelColor.b)
    
    -- Show the border box around the selected player	-- cnicholson: We may enable this at some point.
    --WindowSetShowing (WindowGetParent (windowParent).."Row"..windowIndex.."SelectionBorder", bSelected)	
end

function SocialWindowTabGuild.SetListRowTints()
    for row = 1, SocialWindowTabGuildList.numVisibleRows do
        local row_mod = math.mod(row, 2)
        color = DataUtils.GetAlternatingRowColor( row_mod )
        
        local targetRowWindow = "SocialWindowTabGuildListRow"..row
        WindowSetTintColor(targetRowWindow.."RowBackground", color.r, color.g, color.b )
        WindowSetAlpha(targetRowWindow.."RowBackground", color.a )
    end
end



-- Callback from the <List> that updates a single row.
function SocialWindowTabGuild.UpdatePlayerRow()
    if (SocialWindowTabGuildList.PopulatorIndices ~= nil) then
        local labelName

        for rowIndex, dataIndex in ipairs (SocialWindowTabGuildList.PopulatorIndices) do
            labelName = "SocialWindowTabGuildListRow"..rowIndex.."Name"

            --DEBUG(L"Data Index is "..dataIndex)
            if (dataIndex == SocialWindowTabGuild.SelectedPlayerDataIndex) then
                SocialWindowTabGuild.HighlightPlayerInList (labelName, true, false)
            else				
                SocialWindowTabGuild.HighlightPlayerInList (labelName, false, false)
            end      
        end
    end
end

function SocialWindowTabGuild.OnGuildUpdated()
    SocialWindowTabGuild.playerListNeedsUpdate = true
    UpdatePlayerList()

    -- Set sort button flags
    for index = 2, SocialWindowTabGuild.SORT_TYPE_MAX_NUMBER do
        local window = SocialWindowTabGuild.sortButtons[index]
        ButtonSetStayDownFlag( window, true )
    end
    
    SocialWindowTabGuild.UpdateSortButtons()
end

-- Displays the clicked sort button as pressed down and positions an arrow above it
function SocialWindowTabGuild.UpdateSortButtons()
    
    local type = SocialWindowTabGuild.display.type
    local order = SocialWindowTabGuild.display.order

    for index = 2, SocialWindowTabGuild.SORT_TYPE_MAX_NUMBER do
        local window = SocialWindowTabGuild.sortButtons[index]
        ButtonSetPressedFlag( window, index == SocialWindowTabGuild.display.type )
    end
    
    -- Only move the arrow around for sorting on everything but the name
    if (type > 0) then
          WindowSetShowing( "SocialWindowTabGuildSortButtonBarUpArrow", order == SocialWindowTabGuild.SORT_ORDER_UP )
          WindowSetShowing( "SocialWindowTabGuildSortButtonBarDownArrow", order == SocialWindowTabGuild.SORT_ORDER_DOWN )

        local window = SocialWindowTabGuild.sortButtons[type]
    
        if( order == SocialWindowTabGuild.SORT_ORDER_UP ) then		
            WindowClearAnchors( "SocialWindowTabGuildSortButtonBarUpArrow" )
            WindowAddAnchor("SocialWindowTabGuildSortButtonBarUpArrow", "left", window, "left", 0, 0 )
        else
            WindowClearAnchors( "SocialWindowTabGuildSortButtonBarDownArrow" )
            WindowAddAnchor("SocialWindowTabGuildSortButtonBarDownArrow", "right", window, "right", 0, 0 )
        end
    else
        WindowSetShowing( "SocialWindowTabGuildSortButtonBarUpArrow", false )
        WindowSetShowing( "SocialWindowTabGuildSortButtonBarDownArrow", false )
    end

end

function SocialWindowTabGuild.OnMouseOverPlayerRow()
    local windowIndex	= WindowGetId (SystemData.ActiveWindow.name)
    local windowParent	= WindowGetParent (SystemData.ActiveWindow.name)
    local dataIndex     = ListBoxGetDataIndex (WindowGetParent (windowParent), windowIndex)

    local targetRowWindow = "SocialWindowTabGuildListRow"..windowIndex
    
    SocialWindowTabGuild.SetListRowTints()
    WindowSetTintColor(targetRowWindow.."RowBackground", 66, 35, 0 )

end

function SocialWindowTabGuild.OnMouseOverPlayerRowEnd()
    SocialWindowTabGuild.SetListRowTints()
end

function SocialWindowTabGuild.OnVertScrollLButtonUp()
    -- dummy LButtonUp handler for the scrollbars to stop them from
    -- failing to handle for lack of a LUA script event handler
end

-- Handles the Left Button click on a player row
function SocialWindowTabGuild.OnLButtonUpPlayerRow()
    SocialWindowTabGuild.HighlightPlayerInList (SystemData.ActiveWindow.name, true, true)
end

-- Displays a tooltip with information on the type of sort being hovered over
function SocialWindowTabGuild.OnMouseOverSortButton()
    local windowName	= SystemData.ActiveWindow.name
    local windowIndex	= WindowGetId (windowName)

    Tooltips.CreateTextOnlyTooltip (windowName, nil)
    Tooltips.SetTooltipText (1, 1, SocialWindowTabGuild.ColumnHeaders[windowIndex])
    Tooltips.SetTooltipColorDef (1, 1, Tooltips.COLOR_HEADING)	
    Tooltips.Finalize ()
    
    local anchor = { Point="top", RelativeTo=windowName, RelativePoint="center", XOffset=0, YOffset=-32 }
    Tooltips.AnchorTooltip (anchor)
    Tooltips.SetTooltipAlpha (1)
end

-- Button Callback for the Sort Buttons
function SocialWindowTabGuild.OnSortPlayerList()
    local type = WindowGetId( SystemData.ActiveWindow.name )
    -- If we are already using this sort type, toggle the order.
    if( type == SocialWindowTabGuild.display.type ) then
        if( SocialWindowTabGuild.display.order == SocialWindowTabGuild.SORT_ORDER_UP ) then
            SocialWindowTabGuild.display.order = SocialWindowTabGuild.SORT_ORDER_DOWN
        else
            SocialWindowTabGuild.display.order = SocialWindowTabGuild.SORT_ORDER_UP
        end
        
    -- Otherwise change the type and use the up order.	
    else
        SocialWindowTabGuild.display.type = type
        SocialWindowTabGuild.display.order = SocialWindowTabGuild.SORT_ORDER_UP
    end

    SocialWindowTabGuild.playerListNeedsUpdate = true
    UpdatePlayerList()
    SocialWindowTabGuild.UpdateSortButtons()
end

function SocialWindowTabGuild.OnPressSearchToggleButton()
end

function SocialWindowTabGuild.OnPressSetGuildButton()
    SendGuildOptions(1, 2, L"My Notes")	
end

function SocialWindowTabGuild.OnPressFindButton()
    SendGuildSearchRequest(0)	
end